/**
 * Created by TANG on 2021/3/25.
 */
layui.config({base:'../../layui/dropdown/'})
    .use(['form','table','layedit', 'laydate'], function() {
        var form = layui.form
            , table = layui.table
            , layer = layui.layer
            , layedit = layui.layedit
            , laydate = layui.laydate
            , $ = layui.$;

        table.render({
            elem: '#test'
            ,url: config.gatewayUri+"/"+config.deviceServiceId+"/api/device/admin/getBackDeviceList"
            ,title: 'DeviceTable'
            ,totalRow: true
            ,toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
            ,defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
                title: '提示'
                ,layEvent: 'LAYTABLE_TIPS'
                ,icon: 'layui-icon-tips'
            }]
            ,id : "DeviceTable"
            ,cols: [[
                {type: 'checkbox', fixed: 'left'},
                {field: "deviceid",title:'设备id',align:"center",hide: true},
                {field: 'devicenumber',title:'设备编号',minWidth:200,align:"center",sort:true},
                {field: 'devicename',title:'设备名称',minWidth:200,align:"center",sort:true},
                {field: 'deviceqrcode',title: '二维码',minWidth:120,align:"center",sort:true,templet:function(d){
                    return "<img src='http://localhost:8002/"+ d.deviceqrcode+"' width='30px' height='80px' />";
                }},
                {field: 'venuesid',title:'场地名称',minWidth:200,align:"center",sort:true,templet:function(d){
                    if(d.venuesName != null){
                        return "<span>"+ d.venuesName+"</span>";
                    }else{
                        return "<span></span>";
                    }
                }},
                {field: 'address',title:'设备地址',minWidth:200,align:"center",sort:true},
                {field: 'sortingid',title:'所需分拣中心',minWidth:200,align:"center",sort:true,templet:function(d){
                    return "<span>"+ d.sortingName+"</span>"
                }},
                {field: 'operatorsid',title:'所需运营商',minWidth:200,align:"center",sort:true,templet:function(d){
                    return "<span>"+ d.operatorsName+"</span>"
                }},
                {field: 'partnersid',title:'所需合伙人',minWidth:200,align:"center",sort:true,templet:function(d){
                    return "<span>"+ d.partnersName+"</span>"
                }},
                {field: 'spillover',title:'满溢度',minWidth:120,align:"center",sort:true,templet:function(d){
                    return "<span>"+ d.spillover+"%</span>";
                }},
                {field: 'isstock',title:'商品库存',minWidth:120,align:"center",sort:true,templet:function(d){
                    if(d.isstock == 1){
                        return "<span>正常</span>";
                    }else{
                        return "<span style='color: orange'>缺货</span>";
                    }
                }},
                {field: 'devicestatus',title:'设备状态',minWidth:120,align:"center",sort:true,templet:function(d){
                    if(d.devicestatus == 1){
                        return "<span>正常</span>";
                    }else if(d.devicestatus == 2){
                        return "<span style='color: red'>故障</span>";
                    }else{
                        return "<span style='color: orange'>离线</span>";
                    }
                }},
                {field: 'isflag',title:'营业状态',minWidth:120,align:"center",sort:true,templet:function(d){
                    if(d.isflag == 1){
                        return "<span style='color: red'>禁用</span>";
                    }else{
                        return "<span>正常</span>";
                    }
                }},
                {field: 'ctime',title:'创建时间',minWidth:200,align:"center",sort:true},
                {title:'操作',width:300,fixed:"right",toolbar:'#AppInfoListBar'}
            ]]
            ,page: true
            ,limit:5
            ,limits:[5,10,15,20]
            ,response: {
                statusCode: '200' //重新规定成功的状态码为 200，table 组件默认为 0
            }
            ,parseData: function(res){ //将原始数据解析成 table 组件所规定的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.list //解析数据列表
                };
            }
        });

        $.ajax({
            url: config.gatewayUri+"/"+config.deviceServiceId+"/api/device/admin/getBackDeviceCountStatistics",
            type: "get",
            dataType:"json",
            success:function(res){
                $("#deviceNumber").text(res.data);
            }
        })

        $.ajax({
            url: config.gatewayUri+"/"+config.deviceServiceId+"/api/device/admin/getBackDeviceCountStatistics",
            data:{status:1},
            type: "get",
            dataType:"json",
            success:function(res){
                $("#normalDeviceNumber").text(res.data);
            }
        })

        $.ajax({
            url: config.gatewayUri+"/"+config.deviceServiceId+"/api/device/admin/getBackDeviceCountStatistics",
            data:{status:2},
            type: "get",
            dataType:"json",
            success:function(res){
                $("#malfunctionDeviceNumber").text(res.data);
            }
        })

        $.ajax({
            url: config.gatewayUri+"/"+config.deviceServiceId+"/api/device/admin/getBackDeviceCountStatistics",
            data:{status:3},
            type: "get",
            dataType:"json",
            success:function(res){
                $("#offlineDeviceNumber").text(res.data);
            }
        })

        $.ajax({
            url: config.gatewayUri+"/"+config.deviceServiceId+"/api/device/admin/getBackDeviceCountStatistics",
            data:{isStock:2},
            type: "get",
            dataType:"json",
            success:function(res){
                $("#outofstockDeviceNumber").text(res.data);
            }
        })

        table.on('tool(test)', function(obj){
            var data = obj.data;
            if(obj.event === 'del'){
                layer.confirm('真的删除行么', function(index){
                    deleteAppId(obj.data.deviceid);
                });
            } else if(obj.event === 'edit'){
                layer.open({
                    //调整弹框的大小
                    area:['800px','600px'],
                    title:"修改设备",
                    //动画
                    anim:2,
                    //弹出层的基本类型
                    type: 2,
                    //刚才定义的弹窗页面
                    content:['pages/device/addDevice.html', 'yes'],
                     success: function(layero,index){
                         var body = layer.getChildFrame('body', index);
                         body.find("#deviceid").val(data.deviceid);
                         body.find("#devicenumber").val(data.devicenumber).attr( {"readonly":"readonly","disabled":'disabled'});
                         body.find("#devicename").val(data.devicename);
                         body.find("#rownumber").val(data.rowNumber).attr( {"readonly":"readonly","disabled":'disabled'});
                         body.find("#columnnumber").val(data.columnNumber).attr( {"readonly":"readonly","disabled":'disabled'});
                         body.find("#stockmaxqty").val(data.stockmaxqty);
                         body.find("#stockflag").val(data.stockflag);
                         //body.find("#sortingid").append(new Option(data.sortingName,data.sortingid));
                         body.find("#sorting").val(data.sortingid);
                         body.find("#sortinggrcomrate").val(data.sortinggrcomrate);
                         body.find("#sortinggoodscomrate").val(data.sortinggoodscomrate);
                         //body.find("#operatorsid").append(new Option(data.operatorsName,data.operatorsid));
                         body.find("#operators").val(data.operatorsid);
                         body.find("#operatorsgrcomrate").val(data.operatorsgrcomrate);
                         body.find("#partnersid").append(new Option(data.partnersName,data.partnersid));
                         body.find("#partnersgrcomrate").val(data.partnersgrcomrate);
                         body.find("#partnersgoodscomrate").val(data.partnersgoodscomrate);
                         //body.find("#venuesid").append(new Option(data.venuesName,data.venuesid));
                         body.find("#venues").val(data.venuesid);
                         body.find("#position").append(new Option(data.province + "/" + data.city + "/" + data.area, data.province + "/" + data.city + "/" + data.area));
                         body.find("#address").val(data.address);
                         body.find(".isflag[value='"+data.isflag+"']").attr("checked","true");
                         form.render();
                     }
                });
            }else if(obj.event == 'up'){
                upVrsion(data.deviceid);
            }
        });

        $("#upall").click(function() {
            var checkStatus = table.checkStatus('DeviceTable'),
                data = checkStatus.data,
                deviceid = [];
            if(data.length > 0) {
                for (var i in data) {
                    deviceid.push(data[i].deviceid);
                }
                upVrsion(deviceid);
            }else{
                layer.msg("请选择需要进行升级的设备!");
            }
        });

        $("#addDevice").click(function(){
            layer.open({
                //调整弹框的大小
                area:['800px','600px'],
                title:"新增设备",
                //动画
                anim:2,
                //弹出层的基本类型
                type: 2,
                //刚才定义的弹窗页面
                content:['pages/device/addDevice.html', 'yes']/*,
                success: function(layero,index){
                    var body = layer.getChildFrame('body', index);
                    body.find("#deviceid").val(data);
                    form.render();
                }*/
            });
        });

        form.on('submit(formDemo)', function(data){
            table.reload("DeviceTable",{
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where:data.field
            });
        });

        function deleteAppId(data){
            $.ajax({
                type:"delete",
                url:config.gatewayUri+"/"+config.deviceServiceId+"/api/device/admin/delDevice",
                data:{id:data},
                dataType:"json",
                success:function(result){
                    if(result.code == 200){
                        layer.alert("删除成功!");
                        setTimeout('window.location.reload()',500);
                        /*obj.del();
                        layer.close(index);*/
                    }else{
                        layer.alert(result.msg);
                    }
                },
                error:function(err){
                    layer.alert(err);
                }
            })
        }

        function upVrsion(data){
            layer.open({
                //调整弹框的大小
                area:['700px','200px'],
                title:"版本升级",
                //动画
                anim:2,
                //弹出层的基本类型
                type: 2,
                //刚才定义的弹窗页面
                content:['pages/device/upVersion.html', 'yes'],
                success: function(layero,index){
                    var body = layer.getChildFrame('body', index);
                    body.find("#deviceid").val(data);
                    form.render();
                }
            });
        }

        //日期时间范围
        laydate.render({
            elem: '#test10'
            ,type: 'datetime'
            ,range: true
        });


        $.ajax({
            type:"get",
            url:config.gatewayUri+"/"+config.deviceServiceId+"/api/manager/admin/getManagerList",
            data:{managertype:3},
            dataType:"json",
            success:function(result){
                if(result.code == 200){
                    $.each(result.data,function(index,item){
                        $(".sortingid").append(new Option(item.username,item.managerid));
                    });
                    layui.form.render("select");
                }else{
                    layer.alert(result.msg);
                }
            },
            error:function(result){
                layer.alert(result);
            }
        });

        $.ajax({
            type:"get",
            url:config.gatewayUri+"/"+config.deviceServiceId+"/api/manager/admin/getManagerList",
            data:{managertype:4},
            dataType:"json",
            success:function(result){
                if(result.code == 200){
                    $.each(result.data,function(index,item){
                        $(".operatorsid").append(new Option(item.username,item.managerid));
                    });
                    layui.form.render("select");
                }else{
                    layer.alert(result.msg);
                }
            },
            error:function(result){
                layer.alert(result);
            }
        });

        $.ajax({
            type:"get",
            url:config.gatewayUri+"/"+config.deviceServiceId+"/api/venues/admin/getBackVenuesList",
            dataType:"json",
            success:function(result){
                if(result.code == 200){
                    $.each(result.data,function(index,item){
                        $(".venuesid").append(new Option(item.venuesname,item.venuesid));
                    });
                    layui.form.render("select");
                }else{
                    layer.alert(result.msg);
                }
            },
            error:function(result){
                layer.alert(result);
            }
        })


        form.on('select(operatorsid)', function(data) {
            $(".partnersid").html("");
            if(data.value != "") {
                $.ajax({
                    type: "get",
                    url: config.gatewayUri+"/"+config.deviceServiceId+"/api/partners/admin/getAllPartnersList",
                    data: {fid: data.value},
                    dataType: "json",
                    success: function (result) {
                        if (result.code == 200) {
                            $.each(result.data, function (index, item) {
                                $(".partnersid").append(new Option(item.username, item.partnersid));
                            });
                            layui.form.render("select");
                            return;
                        } else {
                            layer.alert(result.msg);
                        }
                    },
                    error: function (result) {
                        layer.alert(result);
                    }
                });
            }else {
                layui.form.render("select");
            }
        });

        form.on('select(sortingid)', function(data) {
            $(".partnersid").html("");
            if(data.value != "") {
                $.ajax({
                    type: "get",
                    url: config.gatewayUri+"/"+config.deviceServiceId+"/api/partners/admin/getAllPartnersList",
                    data: {fid: data.value},
                    dataType: "json",
                    success: function (result) {
                        if (result.code == 200) {
                            $.each(result.data, function (index, item) {
                                $(".partnersid").append(new Option(item.username, item.partnersid));
                            })
                            layui.form.render("select");
                            return;
                        } else {
                            layer.alert(result.msg);
                        }
                    },
                    error: function (result) {
                        layer.alert(result);
                    }
                });
            }else {
                layui.form.render("select");
            }
        });

        for(var i=1;i<=100;i++){
            $(".spillover").append(new Option(i+"%",i));
        };
    });